import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import { fileURLToPath, URL } from "node:url";
import Components from "unplugin-vue-components/vite";
import { VantResolver } from "unplugin-vue-components/resolvers";
import AutoImport from "unplugin-auto-import/vite";
import UnoCSS from "unocss/vite";
import path from 'path';
import { visualizer } from 'rollup-plugin-visualizer'; // 需要安装此依赖
import dynamicImport from 'vite-plugin-dynamic-import';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    UnoCSS(),
    dynamicImport(),
    AutoImport({
      imports: ["vue", "vue-router"],
      eslintrc: {
        enabled: true,
      },
    }),
    AutoImport({
      resolvers: [VantResolver()],
    }),
    // 自动导入的插件，解析器可以是 vant
    Components({
      dts: false,
      resolvers: [VantResolver({ importStyle: false })],
    }),
    // 构建分析插件，仅在生产环境使用
    process.env.ANALYZE === 'true' && visualizer({
      open: true,
      gzipSize: true,
      brotliSize: true,
      filename: 'dist/stats.html',
    }),
  ],
  server: {
    port: 5174,
    open: true,
    host: "0.0.0.0",
    proxy: {
      // "/api": {
      //   // target: "https://chenyulong.cn", // 目标服务器
      //   target: " http://localhost:3001", // 目标服务器
      //   changeOrigin: true,
      //   // rewrite: (path) => path.replace(/^\/api/, ""),
      // },
      "/api/v1.0": {
        target: "https://tapi.zeehoev.com",
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ""),
      }
    },
  },
  resolve: {
    alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url)),
    },
  },
  build: {
    // 启用CSS代码分割
    cssCodeSplit: true,
    // 减小chunk大小，提高并行加载效率
    chunkSizeWarningLimit: 1500,
    // 分割依赖包
    rollupOptions: {
      output: {
        manualChunks: {
          'vue-vendor': ['vue', 'vue-router', 'pinia'],
          'ui-vendor': ['vant'],
          'echarts': ['echarts']
        },
        // 优化静态资源输出
        assetFileNames: (assetInfo) => {
          const info = assetInfo.name.split('.');
          let extType = info[info.length - 1];
          if (/\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/i.test(assetInfo.name)) {
            extType = 'media';
          } else if (/\.(png|jpe?g|gif|svg|webp)(\?.*)?$/i.test(assetInfo.name)) {
            extType = 'img';
          } else if (/\.(woff2?|eot|ttf|otf)(\?.*)?$/i.test(assetInfo.name)) {
            extType = 'fonts';
          }
          return `assets/${extType}/[name]-[hash][extname]`;
        },
        chunkFileNames: 'assets/js/[name]-[hash].js',
        entryFileNames: 'assets/js/[name]-[hash].js',
      }
    },
    // 启用压缩
    minify: 'terser',
    terserOptions: {
      compress: {
        drop_console: true,
        drop_debugger: true,
      }
    },
    // 启用gzip压缩
    assetsInlineLimit: 4096, // 4kb以下的资源内联为base64
    // 启用sourcemap
    sourcemap: false,
  }
});
